﻿var sessionRecipeId = '' ;

//Grocery
function LoadGroceryUserRecipeView(ingredientList, RecipeName, Serving, ID, ServingSize, department) {
    
//    $('#divGroceryRecipe').remove('.divMessage');
    var ser = ServingSize;
    if (ServingSize == '' || ServingSize == '0') ServingSize = Serving;
    var ArrayIngredient = ingredientList.split('|');
    var html = '';
    html += '<div id=RC' + ID + ' lang="' + RecipeName + '" class="divRecipe">';

    html += '<div class="bg_gray">';
    html += '<div style="width:94%">';
    //    html += '<p class="txt03">' + RecipeName + '</p>&nbsp;&nbsp; <a style="font-size:10px">Serving: ' + ServingSize + '</a>';
    html += '<p class="TitleGrocery">' + RecipeName + '</p><p class="TitleGrocery" style="font-size:10px">Serving: ' + ServingSize + '</p>';
    html += '</div>';
    html += '<div style="float:right; margin-top:-20px; padding-top:-20px">';
    html += '<p class="txt04"><img title="Remove this recipe" src="images/remove.jpg" alt="" onclick="removeRecipe(' + ID + ')" width="22" height="22" /></p>';
    html += '</div>';
    html += '</div>';
    html += '<div class="clearfix clear">';
    html += '<ul id="ul' + ID + '" class="ul03">';
    var i = 1;
    $.each(ArrayIngredient, function (key, ArrayIngredient) {

        var IngredientName = ArrayIngredient;
        if (IngredientName != '') {
            if (IngredientName.substr(0, 1) == ',') IngredientName = IngredientName.substr(1, IngredientName.length);

            if (ser > 0) {
                IngredientName = ChangeServingSize(IngredientName, Serving, ServingSize);
            }
            //
            html += '<li id="ul'+ID+'_lirc' + key + '">';
            html += '<input id="check_box_1_Recipe_' + ID+'_'+key + '" class="css-checkbox" onclick="javascript:RemoveIngredientRecipe(this.id,this.value)" value="' + IngredientName + '" type="checkbox" checked="checked"/>';
            html += '<label id="label_box_1_Recipe_' + ID+'_'+key + '" for="demo_box_1" class="css-label">' + IngredientName + '</label>';
            html += '</li>';
            document.getElementById('hdIngredientDepart').value+=IngredientName+'|';
            i = i + 1;
        }
    });
    html += '</ul>';
    html += '</div>';
    html += '</div>';
    $('.divMessage').remove();
    $('#divGroceryRecipe').append(html);
    document.getElementById('hdShare').value += ingredientList;

    //Call session to save recipeid here
    if (sessionRecipeId == '')
        sessionRecipeId = ID;
    else
        sessionRecipeId = sessionRecipeId + "," + ID;
    //    alert(sessionRecipeId);
    CallSaveSession("sessionRecipeId", sessionRecipeId);
}

function CallSaveSession(key, value) {
    $.ajax({
        type: "POST",
        url: "PIMService.asmx/SaveSession",
        data: "{'key':'" + key + "','value':'" + value + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
        },
        error: function (result) {
        }

    });
}

function findElement(chkid,value)
{
    $('.ul03 li label').each(function () {
        var test = $(this).text();
        if(test==value)
        {
            var id= $(this).attr("id");
            var check=id.replace("label", "check");
            var label=id.replace("check", "label");
            if(id.indexOf('Recipe')>-1)//if recipe then check for depart
            {
                var checked = $('#' + chkid).is(":checked");
                if (checked == true) {
        
                    $('#' + chkid).attr("checked",true);
                    $('#' + check).attr("checked",true);
                    $('#' + label).css("color", "");
                    $('#' + label).css("text-decoration", "none");
                }
                else {
                    $('#' + chkid).attr("checked",false);
                    $('#' + check).attr("checked",false);
                    $('#' + label).css('color', '#D6D4D2');
                    $('#' + label).css("text-decoration", "line-through");
                }
            }
            else if (id.indexOf('Depart') > -1)//if depart then check for recipe
            {
                var checked = $('#' + chkid).is(":checked");
                if (checked == true) {
                    $('#' + check).attr("checked",true);
                    $('#' + chkid).attr("checked",true);
                    $('#' + label).css("color", "");
                    $('#' + label).css("text-decoration", "none");
                }
                else {
                    $('#' + chkid).attr("checked",false);
                    $('#' + check).attr("checked",false);
                    $('#' + label).css('color', '#D6D4D2');
                    $('#' + label).css("text-decoration", "line-through");
                }
            }
        }
    });
}

var AddIndex=0;

function AddAdditional() {
    if ($("#txtAdditional").val() == '') {
        alert('Please input additional.');
        return false;
    }
    var addInfre = '';
    AddIndex++;
//    alert(AddIndex);
    var divAddIngre = $('#RC001');
    if (divAddIngre.length > 0) {
        addInfre += '<li id="ul001_lirc001">';
        addInfre += '<input id="check_AddRecipe_box_1_001_'+AddIndex.toString()+'" class="css-checkbox" onclick="javascript:RemoveIngredientRecipe(this.id,this.value)" value="' + $("#txtAdditional").val() + '" type="checkbox" checked="checked"/>';
        addInfre += '<label id="label_AddRecipe_box_1_001_'+AddIndex.toString()+'" for="demo_box_1" class="css-label">' + $("#txtAdditional").val() + '</label>';
        addInfre += '</li>';
        $('#RCul001').prepend(addInfre);
    }
    else {
        addInfre += '<div id="RC001" lang="Additional" class="divRecipe">';
        addInfre += '<div class="bg_gray">';
        addInfre += '<p class="txt03">Additional</p>&nbsp;&nbsp; Serving: ' + $("#txtServing").val();
        addInfre += '<p class="txt04"><img title="Remove this recipe" src="images/remove.jpg" alt="" onclick="RemoveRecipeAdd()" width="22" height="22" /></p>';
        addInfre += '</div>';
        addInfre += '<div class="clearfix clear">';
        addInfre += '<ul id="RCul001" class="ul03">';

        addInfre += '<li id="RCul001_lirc001">';
        addInfre += '<input id="check_AddRecipe_box_1_001_'+AddIndex.toString()+'" class="css-checkbox" onclick="javascript:RemoveIngredientRecipe(this.id,this.value)" value="' + $("#txtAdditional").val() + '" type="checkbox" checked="checked"/>';
        addInfre += '<label id="label_AddRecipe_box_1_001_'+AddIndex.toString()+'" for="demo_box_1" class="css-label">' + $("#txtAdditional").val() + '</label>';
        addInfre += '</li>';

        addInfre += '</ul>';
        addInfre += '</div>';
        addInfre += '</div>';
        $('#divGroceryRecipe').prepend(addInfre);
    }

    var addDepart = '';            
    var divAddDepart = $('#depart_001');
    if (divAddDepart.length > 0) {
        addDepart += '<li id="ul001_ligro001">';
        addDepart += '<input id="check_AddDepart_box_1_001_'+AddIndex.toString()+'" class="css-checkbox" onclick="javascript:RemoveIngredientDepart(this.id,this.value)" value="' + $("#txtAdditional").val() + '" type="checkbox" checked="checked"/>';
        addDepart += '<label id="label_AddDepart_box_1_001_'+AddIndex.toString()+'" for="demo_box_1" class="css-label">' + $("#txtAdditional").val() + '</label>';
        addDepart += '</li>';
        $('#ul001').prepend(addDepart);
    }
    else {
        addDepart = '<div id="depart_001" lang="Additional" title="Additional" class="divDepart">';
        addDepart += '<div class="bg_gray">';
        addDepart += '<p class="txt03">Additional</p>&nbsp;&nbsp;';
        addDepart += '<p class="txt04"><img title="Remove this department" onclick="RemoveDepartAdd()" src="images/remove.jpg" alt="" width="22" height="22" /></p>';
        addDepart += '</div>';
        addDepart += '<div class="clearfix clear">';
        addDepart += '<ul id="ul001" class="ul03">';
        addDepart += '<li id="ul001_ligro001">';
        addDepart += '<input id="check_AddDepart_box_1_001_'+AddIndex.toString()+'" class="css-checkbox" onclick="javascript:RemoveIngredientDepart(this.id,this.value)" value="' + $("#txtAdditional").val() + '" type="checkbox" checked="checked"/>';
        addDepart += '<label id="label_AddDepart_box_1_001_'+AddIndex.toString()+'" for="demo_box_1" class="css-label">' + $("#txtAdditional").val() + '</label>';
        addDepart += '</li>';
        addDepart += '</ul>';
        addDepart += '</div>';
        addDepart += '</div>';
        $('#divAdditionalDepart').prepend(addDepart);
    }
    document.getElementById('hdAddingredient').value=document.getElementById('hdAddingredient').value+","+$("#txtAdditional").val()
    $("#txtAdditional").val('');
    return false;
}

function RemoveIngredientRecipe(chkid, value) {
    var checked = $('#' + chkid).is(":checked");
    var label=chkid.replace("check", "label");
    findElement(chkid,value);
    if (checked == true) {
        
        $('#' + chkid).attr("checked",true);
        $('#' + label).css("color", "");
        $('#' + label).css("text-decoration", "none");
    }
    else {
        $('#' + chkid).attr("checked",false);
        
        $('#' + label).css('color', '#D6D4D2');
        $('#' + label).css("text-decoration", "line-through");
    }
}

function RemoveDepartAdd(ID){
    $('#depart_001').remove();
}

function RemoveRecipeAdd(){
    $('#RC001').remove();
}

function removeRecipe(ID) {
    $('#RC' + ID).remove();
}

function ChangeServingSize(IngrediengName, Serving, ServingSize) {
    var pattern = /^\S+/;
    var pattern1 = /[^a-z]+/gi;
    var osv = IngrediengName.match(pattern);
    if (osv == null) osv = 1;
    var regixchar = osv.toString().match(pattern1);
    if (regixchar == null) {
        //alert(regixchar);
        return IngrediengName;
    }
    osv = regixchar;
    var newosv;
    if (osv.toString().indexOf('-') > -1) {
        //alert('1');
        var arr = osv.toString().split('-');
        if (!arr[0].trim())
            return IngrediengName;
        var newsering1 = arr[0] * ServingSize / Serving;
        var newserving2 = arr[1] * ServingSize / Serving;
        var newserving = Ratio.parse(newsering1).simplify().toLocaleString() + '-' + Ratio.parse(newserving2).simplify().toLocaleString();
        return IngrediengName.replace(osv, newserving);
    }
    {
        var newosv = convertfraction(osv);
        var newserving = newosv * ServingSize / Serving;
        var nsv = Ratio.parse(newserving).simplify().toLocaleString();
        return IngrediengName.replace(osv, nsv)
    }
}

function convertfraction(x) {
    var y = x.toString().split(' ');
    if (y.length > 1) {
        var z = y[1].split('/');
        return +y[0] + (z[0] / z[1]);
    }
    else {
        var z = y[0].split('/');
        if (z.length > 1) {
            return z[0] / z[1];
        }
        else {
            return z[0];
        }
    }

}

//function ChangeServingSize(IngrediengName, Serving, ServingSize) {
//    var Ingredieng=IngrediengName;
//    var number=Ingredieng.replace(/[^0-9/]/g, '');
//    var tu = 1;
//    var mau = 1;
//    var old = number;
//    var oldserving = number;
//    var oldSer=0;
//    if (old.indexOf('/') > -1) {
//        var oldServingSplit = old.split('/');
//        tu = parseFloat(oldServingSplit[0]);
//        mau = parseFloat(oldServingSplit[1]);
//    }
//    else {
//        tu = number;
//        mau = 1;
//    }
//    oldSer = tu / mau;

//    var newserving = 0;
//    newserving = parseFloat(oldSer) * parseFloat(ServingSize) / parseFloat(Serving);
//    var nsv = newserving;
//    if (nsv.toString().length > 3) {
//        nsv = nsv.toFixed(2);
//    }
//    
//    var ServingArray = ["7.875","7.75","7.625","7.5","7.375","7.25","7.125","6.67","1.67","0.33","5.33","2.67","1.33","6.875","6.75","6.625","6.5","6.375","6.25","6.125","5.875","5.75","5.625","5.5","5.375","5.25","5.125","4.875","4.75","4.625","4.5","4.375","4.25","4.125","3.875","3.75","3.625","3.5","3.375","3.25","3.125","2.875","2.75","2.625","2.5","2.375","2.25","2.125","1.875","1.75","1.625","1.5","1.375","1.25","1.125","0.875","0.75","0.625","0.5","0.375","0.25","0.125"];
//    var NewServingArray = ["7 7/8","7 3/4","7 5/8","7 1/2","7 3/8","7 1/4","7 1/6","6 2/3","1 2/3","1/3","5 1/3","2 2/3","1 1/3","6 7/8","6 3/4","6 5/8","6 1/2","6 3/8","6 1/4","6 1/8","5 7/8","5 3/4","5 5/8","5 1/2","5 3/8","5 1/4","5 1/8","4 7/8","4 3/4","4 5/8","4 1/2","4 3/8","4 1/4","4 1/8","3 7/8","3 3/4","3 5/8","3 1/2","3 3/8","3 1/4","3 1/8","2 7/8","2 3/4","2 5/8","2 1/2","2 3/8","2 1/4","2 1/8","1 7/8","1 3/4","1 5/8","1 1/2","1 3/8","1 1/4","1 1/8","7/8","3/4","5/8","1/2","3/8","1/4","1/8"];
//    var element = jQuery.inArray(nsv.toString(), ServingArray);
//    var newSer=nsv;
//    
//    if(element!='-1')
//    {
//    newSer=NewServingArray[element];
//    if(newSer==undefined)newSer=nsv.toString();
//    }

//    var nameingredient=Ingredieng.replace(oldserving, newSer);
//    return nameingredient;
//}

function LoadGroceryUserDepartView(department, ingredient) {
//    IngredientName = ingredient;
    var lastChar = department.substr(department.length - 1);
    if (lastChar == ',') department = department.substr(0, department.length - 1);
    var Depart = department.split(',');
    var html = '';
    $('#divGroceryDepart').html(html);
    var DepartMentName = '';
    
    $.each($.unique(Depart), function (i, value) {
        if (DepartMentName == '')
            DepartMentName = value;
        else{
            if(DepartMentName.indexOf(value) == -1){
                DepartMentName = DepartMentName+',' + value;
            }
            
        }
    })
    DepartMentName = DepartMentName + ',';
    var IngredientName = '';
    var Ingredi = ingredient.split('|');
    
    $.each($.unique(Ingredi), function (i, v) {
        if (IngredientName == '')
            IngredientName = v;
        else {
            if (IngredientName.indexOf(v) == -1) {
                IngredientName = IngredientName + '|' + v;
            }

        }
    })
    IngredientName = IngredientName + '|';
    var i = 0;
    if (DepartMentName != '') {
        var departmn = DepartMentName.split(',');
        
        $.each(departmn, function (key, depa) {
            i = key;
            var dp = depa;
            if (dp != '') {
                html += '<div id="depart_' + key + '" lang="' + dp + '" title="' + IngredientName + '" class="divDepart">';
                html += '<div class="bg_gray">';
                html += '<div style="width:94%">';
                html += '<p class="txt03">' + dp + '</p>&nbsp;&nbsp;';
                html += '</div>';
                html += '<div style="float:right; margin-top:-20px; padding-top:-20px">';
                html += '<p class="txt04"><img title="Remove this department" onclick="RemoveDepart(' + key + ')" src="images/remove.jpg" alt="" width="22" height="22" /></p>';
                html += '</div>';
                html += '</div>';
                html += '</div>';
            }

        });
        $('#divGroceryDepart').html(html);
    }

    if ($('#divGroceryDepart').find('div.divDepart').length > 0) {
        for (var j = 0; j <= i; j++) {
            var id = 'depart_' + j;
            var dep = $('#'+id).attr('lang');
            var ingre = $('#' + id).attr('title');
            RenderGrocery(id, dep, ingre);
        }
    }
}

function RemoveDepart(ID) {
    $('#depart_' + ID).remove();
}

function SetHtmlToPrint() {
    var departview=$('#divGroceryDepart').css('display');
    if(departview=='none'){        
        $('#divIngredientPrintDepart').html($('#divGroceryRecipe').html());
    }
    else{
        $('#divIngredientPrintDepart').html($('#divAdditionalDepart').html()+$('#divGroceryDepart').html());
    }
}


function RenderGrocery(id, depart, IngredientName) {
    
    $.ajax({
        type: "POST",
        url: "PIMService.asmx/getIngredientDeptDetail",
        data: "{'ingredientName':'" + IngredientName + "','GroDept':'" + depart + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            var html = '';
            var IngredientDetail = result.d;
            var grodpt = IngredientDetail[0].GroDept;
            html += '<div class="clearfix clear">';
            html += '<ul id="ul'+id+'" class="ul03">';
            for (var j = 0; j < IngredientDetail.length; j++) {
                var ingre = IngredientDetail[j].ingre;
                
                html += '<li id="ul'+id+'_ligro' + j + '">';
                html += '<input id="check_box_1_Depart_ul_' + id+'_'+j + '" class="css-checkbox" onclick="javascript:RemoveIngredientDepart(this.id,this.value)" value="' + ingre + '" type="checkbox" checked="checked"/>';
                html += '<label id="label_box_1_Depart_ul_' + id+'_'+j + '" for="demo_box_1" class="css-label">' + ingre + '</label>';
                html += '</li>';
            }
            html += '</ul>';
            html += '</div>';
            $('#' + id).append(html);
        },
        error: function (result) {
        }

    });

}
var ingredientCheck='';
function RemoveIngredientDepart(chkid, value) {
    
    var checked = $('#' + chkid).is(":checked");
    var label=chkid.replace("check", "label");
    findElement(chkid,value);
    if (checked == true) {
        ingredientCheck=ingredientCheck.replace(value,"");
        $('#' + chkid).attr("checked",true);
        $('#' + label).css("color", "");
        $('#' + label).css("text-decoration", "none");
    }
    else {
        $('#' + chkid).attr("checked",false);
        ingredientCheck+=value+"|";
        $('#' + label).css('color', '#D6D4D2');
        $('#' + label).css("text-decoration", "line-through");
    }
}